﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OPTFleet.OPTFleet;
using System.Diagnostics;
using OPTFleet.Data;
using System.Drawing.Imaging;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace OPTFleet
{
    public partial class MainWindow : Form
    {
        private enum viewState { Init, Planeamentos, Veiculos, Funcionarios, Encomendas, Clientes, Stock }
        private enum editState { Adicionar, Editar , View }
        private viewState state;
        private editState addEdit;
        private CamadaDados cd;
        private CamadaDados.permissao permissao;
        private string user;
        private Object data;
        private int selectedIndex = -1;
        private bool setSelectedIndex = false;
        private Operacoes op;

        public MainWindow(CamadaDados c, CamadaDados.permissao p, string u)
        {
            cd = c;
            op = new Operacoes(cd);
            permissao = p;
            user = u;

            // Initialization of window components()
            InitializeComponent();
            loginStatus.Text = user;

            // Hide all information panels (since no view state is selected)
            funcionariosPanel.Hide();
            planeamentosPanel.Hide();
            veiculosPanel.Hide();
            encomendasPanel.Hide();
            clientesPanel.Hide();
            stocksPanel.Hide();

            // Set features according to permission
            switch (permissao)
            {
                case CamadaDados.permissao.Gestor:
                    editarButton.Enabled = false;
                    adicionarButton.Enabled = false;
                    removerButton.Enabled = false;
                    calcularButton.Enabled = false;
                    break;
                case CamadaDados.permissao.Motorista:
                    editarButton.Enabled = false;
                    adicionarButton.Enabled = false;
                    removerButton.Enabled = false;
                    veiculosButton.Enabled = false;
                    funcionariosButton.Enabled = false;
                    encomendasButton.Enabled = false;
                    clientesButton.Enabled = false;
                    stocksButton.Enabled = false;
                    calcularButton.Enabled = false;
                    break;
                default:
                    break;
            }

            addEdit = editState.View;
        }

        private void planeamentosButton_Click(object sender, EventArgs e)
        {
            if (state == viewState.Planeamentos) return;
            
            // Verify if another state is being edited
            if (addEdit != editState.View)
            {
                if (!ignoreEditMessage())
                {
                    resetTextBoxes();
                    addEdit = editState.View;
                }
                else return;
            }

            // Clears text boxes
            clearTextBoxes();
            
            // Set current view state
            state = viewState.Planeamentos;

            // Enable/Disable 'add', 'remove' and 'edit' buttons
            adicionarButton.Enabled = false;
            editarButton.Enabled = false;
            removerButton.Enabled = false;

            // Show/Hide information panels
            funcionariosPanel.Hide();
            veiculosPanel.Hide();
            planeamentosPanel.Show();
            encomendasPanel.Hide();
            clientesPanel.Hide();
            stocksPanel.Hide();

            // Disable cargo visualization in the 'File' menu
            visualizarCargaToolStripMenuItem.Enabled = false;
            // Disable route visualization in the 'File' menu
            visualizarRotaToolStripMenuItem.Enabled = false;

            // Keep the selected view state checked
            planeamentosButton.Checked = true;
            veiculosButton.Checked = false;
            funcionariosButton.Checked = false;
            encomendasButton.Checked = false;
            clientesButton.Checked = false;
            stocksButton.Checked = false;

            // Clear dataListBox and shows a list of all delivery plans
            refreshListBox();
        }

        private void veiculosButton_Click(object sender, EventArgs e)
        {
            if (state == viewState.Veiculos) return;

            // Verify if another state is being edited
            if (addEdit != editState.View)
            {
                if (ignoreEditMessage())
                {
                    resetTextBoxes();
                    addEdit = editState.View;
                }
                else return;
            }

            // Clears text boxes
            clearTextBoxes();
            
            // Set current view state
            state = viewState.Veiculos;

            // Enable/Disable 'add', 'remove' and 'edit' buttons
            if (permissao == CamadaDados.permissao.Admin)
            {
                adicionarButton.Enabled = true;
                removerButton.Enabled = false;
                editarButton.Enabled = false;
            }
            else
            {
                adicionarButton.Enabled = false;
                removerButton.Enabled = false;
                editarButton.Enabled = false;
            }

            // Show/Hide information panels
            funcionariosPanel.Hide();
            veiculosPanel.Show();
            planeamentosPanel.Hide();
            encomendasPanel.Hide();
            clientesPanel.Hide();
            stocksPanel.Hide();

            // Disable cargo visualization in the 'File' menu
            visualizarCargaToolStripMenuItem.Enabled = false;
            // Disable route visualization in the 'File' menu
            visualizarRotaToolStripMenuItem.Enabled = false;

            // Keep the selected view state checked
            planeamentosButton.Checked = false;
            veiculosButton.Checked = true;
            funcionariosButton.Checked = false;
            encomendasButton.Checked = false;
            clientesButton.Checked = false;
            stocksButton.Checked = false;

            // Clear dataListBox and shows a list of all vehicles
            refreshListBox();
        }

        private void funcionariosButton_Click(object sender, EventArgs e)
        {
            if (state == viewState.Funcionarios) return;

            // Verify if another state is being edited
            if (addEdit != editState.View)
            {
                if (ignoreEditMessage())
                {
                    resetTextBoxes();
                    addEdit = editState.View;
                }
                else return;
            }

            // Clears text boxes
            clearTextBoxes();

            // Set current view state
            state = viewState.Funcionarios;

            // Enable/Disable 'add', 'remove' and 'edit' buttons
            if (permissao == CamadaDados.permissao.Admin)
            {
                adicionarButton.Enabled = true;
                removerButton.Enabled = false;
                editarButton.Enabled = false;
            }
            else
            {
                adicionarButton.Enabled = false;
                removerButton.Enabled = false;
                editarButton.Enabled = false;
            }

            // Show/Hide information panels
            funcionariosPanel.Show();
            veiculosPanel.Hide();
            planeamentosPanel.Hide();
            encomendasPanel.Hide();
            clientesPanel.Hide();
            stocksPanel.Hide();

            // Disable cargo visualization in the 'File' menu
            visualizarCargaToolStripMenuItem.Enabled = false;
            // Disable route visualization in the 'File' menu
            visualizarRotaToolStripMenuItem.Enabled = false;

            // Keep the selected view state checked
            planeamentosButton.Checked = false;
            veiculosButton.Checked = false;
            funcionariosButton.Checked = true;
            encomendasButton.Checked = false;
            clientesButton.Checked = false;
            stocksButton.Checked = false;

            // Clear dataListBox and shows a list of all vehicles
            refreshListBox();
        }

        private void encomendasButton_Click(object sender, EventArgs e)
        {
            if (state == viewState.Encomendas) return;

            // Verify if another state is being edited
            if (addEdit != editState.View)
            {
                if (ignoreEditMessage())
                {
                    resetTextBoxes();
                    addEdit = editState.View;
                }
                else return;
            }

            // Clears text boxes
            clearTextBoxes();

            // Set current view state
            state = viewState.Encomendas;

            // Enable/Disable 'add', 'remove' and 'edit' buttons
            adicionarButton.Enabled = false;
            removerButton.Enabled = false;
            editarButton.Enabled = false;

            // Show/Hide information panels
            funcionariosPanel.Hide();
            veiculosPanel.Hide();
            planeamentosPanel.Hide();
            encomendasPanel.Show();
            clientesPanel.Hide();
            stocksPanel.Hide();

            // Disable cargo visualization in the 'File' menu
            visualizarCargaToolStripMenuItem.Enabled = false;
            // Disable route visualization in the 'File' menu
            visualizarRotaToolStripMenuItem.Enabled = false;

            // Keep the selected view state checked
            planeamentosButton.Checked = false;
            veiculosButton.Checked = false;
            funcionariosButton.Checked = false;
            encomendasButton.Checked = true;
            clientesButton.Checked = false;
            stocksButton.Checked = false;

            // Clear dataListBox and shows a list of all vehicles
            refreshListBox();
        }

        private void clientesButton_Click(object sender, EventArgs e)
        {
            if (state == viewState.Clientes) return;

            // Verify if another state is being edited
            if (addEdit != editState.View)
            {
                if (ignoreEditMessage())
                {
                    resetTextBoxes();
                    addEdit = editState.View;
                }
                else return;
            }

            // Clears text boxes
            clearTextBoxes();

            // Set current view state
            state = viewState.Clientes;

            // Enable/Disable 'add', 'remove' and 'edit' buttons
            adicionarButton.Enabled = false;
            removerButton.Enabled = false;
            editarButton.Enabled = false;

            // Show/Hide information panels
            funcionariosPanel.Hide();
            veiculosPanel.Hide();
            planeamentosPanel.Hide();
            encomendasPanel.Hide();
            clientesPanel.Show();
            stocksPanel.Hide();

            // Disable cargo visualization in the 'File' menu
            visualizarCargaToolStripMenuItem.Enabled = false;
            // Disable route visualization in the 'File' menu
            visualizarRotaToolStripMenuItem.Enabled = false;

            // Keep the selected view state checked
            planeamentosButton.Checked = false;
            veiculosButton.Checked = false;
            funcionariosButton.Checked = false;
            encomendasButton.Checked = false;
            clientesButton.Checked = true;
            stocksButton.Checked = false;

            // Clear dataListBox and shows a list of all clients
            refreshListBox();
        }

        private void stocksButton_Click(object sender, EventArgs e)
        {
            if (state == viewState.Stock) return;

            // Verify if another state is being edited
            if (addEdit != editState.View)
            {
                if (ignoreEditMessage())
                {
                    resetTextBoxes();
                    addEdit = editState.View;
                }
                else return;
            }

            // Clears text boxes
            clearTextBoxes();

            // Set current view state
            state = viewState.Stock;

            // Enable/Disable 'add', 'remove' and 'edit' buttons
            adicionarButton.Enabled = false;
            removerButton.Enabled = false;
            editarButton.Enabled = false;

            // Show/Hide information panels
            funcionariosPanel.Hide();
            veiculosPanel.Hide();
            planeamentosPanel.Hide();
            encomendasPanel.Hide();
            clientesPanel.Hide();
            stocksPanel.Show();

            // Disable cargo visualization in the 'File' menu
            visualizarCargaToolStripMenuItem.Enabled = false;
            // Disable route visualization in the 'File' menu
            visualizarRotaToolStripMenuItem.Enabled = false;

            // Keep the selected view state checked
            planeamentosButton.Checked = false;
            veiculosButton.Checked = false;
            funcionariosButton.Checked = false;
            encomendasButton.Checked = false;
            clientesButton.Checked = false;
            stocksButton.Checked = true;

            // Clear dataListBox and shows a list of all products in stock
            refreshListBox();
        }

        private void calcularButton_Click(object sender, EventArgs e)
        {
            NewRoutes nr = new NewRoutes(op,cd);
            this.AddOwnedForm(nr);
            nr.ShowDialog(this);
            refreshListBox();
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Logout from current user
            this.DialogResult = DialogResult.OK;
            this.Hide();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Exit the application
            this.Close();
        }

        private void editarButton_Click(object sender, EventArgs e)
        {
            editarButton.Enabled = false;
            adicionarButton.Enabled = false;
            removerButton.Enabled = false;

            addEdit = editState.Editar;

            // Make text boxes editable
            editableTextBoxes();
        }

        private void adicionarButton_Click(object sender, EventArgs e)
        {

            editarButton.Enabled = false;
            adicionarButton.Enabled = false;
            removerButton.Enabled = false;

            addEdit = editState.Adicionar;

            // Unselect whatever is selecter (if so)
            if (dataListBox.SelectedIndex >= 0)
                dataListBox.SetSelected(dataListBox.SelectedIndex, false);

            // Clear the text boxes
            clearTextBoxes();

            // Make text boxes editable
            editableTextBoxes();
            if(state==viewState.Funcionarios)
            {
                cargoFuncionariosComboBox.Enabled = true;
                //Image image = Image.FromFile("noimage.png");
              
                FileStream foto = new FileStream("resources\\noimage.png",FileMode.Open);
                System.Drawing.Image image = new Bitmap(foto);
                foto.Close();

                fotoFuncionarioPictureBox.Image = image;
            }
        }

        private void removerButton_Click(object sender, EventArgs e)
        {
            switch(state)
            {
                case viewState.Funcionarios:
                    Object[] args = { data };
                    cd.OperacaoDados(CamadaDados.OP_REMOVE_FUNCIONARIO, args);
                    break;
                case viewState.Veiculos:
                    Object[] argv = { ((Veiculo)data).IDveiculo };
                    cd.OperacaoDados(CamadaDados.OP_REMOVE_VEICULO, argv);
                    break;
                default:
                    break;
            }

            data = null;
            resetTextBoxes();
            refreshListBox();
            /*
            Local teste = new Local(1,"Rua Engenheiro Afonso José Fonseca", "13", "Braga", "Braga", "4715");
            Local.Geocode(teste.ToString());
            visualizarRotaToolStripMenuItem_Click(null, null);

            List<long> direcoes = Operacoes.CreateRoute("41.54,-8.4;41.5,-8.2;41,8;40,9");
            foreach(long s in direcoes)
                Console.WriteLine(s.ToString()+"\n");*/
        }

        private void guardarButton_Click(object sender, EventArgs e)
        {
            // Check for empty text boxes
            if (!checkTextBoxes()) return;

            // Set text boxes as read only
            lockTextBoxes();
            if (state == viewState.Funcionarios) procurarFuncionariosButton.Hide();

            //Insert database information and interface
            switch(state)
            {
                case viewState.Funcionarios:
                    Funcionario f;
                    MemoryStream ms = new MemoryStream();
                    fotoFuncionarioPictureBox.Image.Save(ms, ImageFormat.Png);
                    byte[] foto = ms.GetBuffer();
                    bool b = (dispFuncionariosTextBox.Text.Equals("Disponível"))?true:false;
                    int idf = (idFuncionarioTextBox.Text.Equals("")) ? 12345 : int.Parse(idFuncionarioTextBox.Text);
                    if (cargoFuncionariosComboBox.SelectedIndex == 1)
                    {
                        f = new Gestor(idf, nomeFuncionarioTextBox.Text, b, foto);
                    }
                    else
                    {
                        if (cargoFuncionariosComboBox.SelectedIndex == 0)
                        {
                            int i = 0;
                            SortedSet<int> tipos = new SortedSet<int>();
                            CheckedListBox.CheckedIndexCollection c = tipoVeiculoFuncionariosCheckedListBox.CheckedIndices;
                            for (i = 0; i < c.Count; i++)
                            {
                                tipos.Add(c[i]);
                            }
                            f = new Motorista(idf, nomeFuncionarioTextBox.Text, b, foto, tipos);
                        }
                        else
                        {
                            f = new Admin(idf,nomeFuncionarioTextBox.Text,b,foto);
                        }
                    }
                    object[] a = { f };
                    if (addEdit == editState.Adicionar)
                    {
                        cd.OperacaoDados(CamadaDados.OP_INSERIR_FUNCIONARIO, a);
                    }
                    else
                    {
                        cd.OperacaoDados(CamadaDados.OP_UPDATE_FUNCIONARIO, a);
                    }
                    if (permissao == CamadaDados.permissao.Admin)
                    {
                        adicionarButton.Enabled = true;
                        editarButton.Enabled = true;
                        removerButton.Enabled = true;
                    }
                    break;
                  
                case viewState.Veiculos:
                    string ss = tipoVeiculoTextBox.Text;
                    int tipo;
                    if(ss.Equals("Ligeiro")){
                        tipo = Veiculo.LIGEIRO;
                    }else if(ss.Equals("Semi-Pesado")){
                        tipo = Veiculo.SEMIPESADO;
                    }else tipo = Veiculo.PESADO;
                    int idv = (idVeiculoTextBox.Text.Equals(""))?12345:int.Parse(idVeiculoTextBox.Text);
                    Veiculo v = new Veiculo(idv, matriculaVeiculoTextBox.Text,tipo,anoVeiculosTimePicker.Value,double.Parse(larguraVeiculoTextBox.Text),double.Parse(comprimentoVeiculoTextBox.Text),int.Parse(depositoVeiculoTextBox.Text),double.Parse(consumoVeiculoTextBox.Text));
                    object[] args = { v };
                    if(addEdit == editState.Adicionar)
                    {
                        cd.OperacaoDados(CamadaDados.OP_INSERIR_VEICULO, args);
                    }
                    else
                    {
                        cd.OperacaoDados(CamadaDados.OP_UPDATE_VEICULO,args);
                    }
                    if (permissao == CamadaDados.permissao.Admin)
                    {
                        adicionarButton.Enabled = true;
                        editarButton.Enabled = true;
                        removerButton.Enabled = true;
                    }
                    break;

                case viewState.Planeamentos:
                    break;

                default:
                    break;
            }
            addEdit = editState.View;
            refreshListBox();
        }

        // Refreshes list box
        private void refreshListBox()
        {
            SortedDictionary<int, string> lista;
            SortedSet<int> lista2;

            dataListBox.Items.Clear();
            switch (state)
            {
                case viewState.Clientes:
                    lista = (SortedDictionary<int,string>)cd.OperacaoDados(CamadaDados.OP_GETLISTCLIENTES, null);
                    foreach (int i in lista.Keys)
                        dataListBox.Items.Add(i+" - "+lista[i]);
                    break;

                case viewState.Encomendas:
                    lista2 = (SortedSet<int>)cd.OperacaoDados(CamadaDados.OP_GETLISTENCOMENDAS, null);
                    foreach (int i in lista2)
                        dataListBox.Items.Add(i);
                    break;

                case viewState.Funcionarios:
                    lista = (SortedDictionary<int, string>)cd.OperacaoDados(CamadaDados.OP_GETLISTFUNCIONARIOS, null);
                    foreach (int i in lista.Keys)
                        dataListBox.Items.Add(i + " - " + lista[i]);
                    break;

                case viewState.Planeamentos:
                    lista2 = (SortedSet<int>)cd.OperacaoDados(CamadaDados.OP_GETLISTPLANEAMENTOS, null);
                    foreach (int i in lista2)
                        dataListBox.Items.Add(i);
                    break;

                case viewState.Stock:
                    SortedSet<string> lista3 = (SortedSet<string>)cd.OperacaoDados(CamadaDados.OP_GETLISTSTOCK, null);
                    foreach (string s in lista3)
                        dataListBox.Items.Add(s);
                    break;

                case viewState.Veiculos:
                    lista = (SortedDictionary<int, string>)cd.OperacaoDados(CamadaDados.OP_GETLISTVEICULOS, null);
                    foreach (int i in lista.Keys)
                        dataListBox.Items.Add(i + " - " + lista[i]);
                    break;

                default:
                    break;
            }
        }

        // Asks if the user wants to discard the changes he made (and reset text boxes if so)
        private bool ignoreEditMessage()
        {
            if (MessageBox.Show("Deseja ignorar as mudanças que efectuou?", "Ignorar mudanças", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                return (true);
            }
            else return (false);
        }

        // Resets text boxes to their normal state
        private void resetTextBoxes()
        {
            // Sets text boxes as read only
            lockTextBoxes();
            // Clears text boxes
            clearTextBoxes();
        }

        // Checks for empty text boxes
        private bool checkTextBoxes()
        {
            bool ret = true;
            switch (state)
            {
                case (viewState.Funcionarios):
                    if(cargoFuncionariosComboBox.SelectedIndex < 0) ret=false;
                    if(nomeFuncionarioTextBox.Text.Equals("")) ret=false;
                    if(dispFuncionariosTextBox.Text.Equals("")) ret=false;
                    if(fotoFuncionarioPictureBox.Image == null) ret = false;
                    break;
                case (viewState.Planeamentos):
                    break;
                case (viewState.Veiculos):
                    if(matriculaVeiculoTextBox.Text.Equals("")) ret=false;
                    if(tipoVeiculoTextBox.Text.Equals("")) ret=false;
                    if(anoVeiculosTimePicker.Value == null) ret = false;
                    if(larguraVeiculoTextBox.Text.Equals("")) ret=false;
                    if(comprimentoVeiculoTextBox.Text.Equals("")) ret=false;
                    if(depositoVeiculoTextBox.Text.Equals("")) ret=false;
                    if (consumoVeiculoTextBox.Text.Equals("")) ret = false;
                    break;
                default:
                    break;
            }
            return(ret);
        }

        // Sets text boxes as read only
        private void lockTextBoxes()
        {
            switch(state)
            {
                case(viewState.Funcionarios):
                    cargoFuncionariosComboBox.Enabled = false;
                    nomeFuncionarioTextBox.ReadOnly = true;
                    dispFuncionariosTextBox.ReadOnly = true;
                    tipoVeiculoFuncionariosCheckedListBox.Enabled = false;
                    procurarFuncionariosButton.Hide();

                    guardarButton.Hide();
                    this.funcionariosPanel.Controls.Remove(this.guardarButton);
                    break;
                case(viewState.Planeamentos):
                    dataGridView1.Enabled = false;

                    this.planeamentosPanel.Controls.Remove(this.guardarButton);
                    guardarButton.Hide();
                    break;
                case(viewState.Veiculos):
                    matriculaVeiculoTextBox.ReadOnly = true;
                    tipoVeiculoTextBox.ReadOnly = true;
                    anoVeiculosTimePicker.Enabled = false;
                    larguraVeiculoTextBox.ReadOnly = true;
                    comprimentoVeiculoTextBox.ReadOnly = true;
                    depositoVeiculoTextBox.ReadOnly = true;
                    consumoVeiculoTextBox.ReadOnly = true;

                    guardarButton.Hide();
                    this.veiculosPanel.Controls.Remove(this.guardarButton);
                    break;
                default:
                    break;
            }
        }

        // Makes text boxes editable
        private void editableTextBoxes()
        {
            switch(state)
            {
                case(viewState.Funcionarios):
                    nomeFuncionarioTextBox.ReadOnly = false;
                    dispFuncionariosTextBox.ReadOnly = false;
                    procurarFuncionariosButton.Show();
                    tipoVeiculoFuncionariosCheckedListBox.Enabled = true;

                    if (addEdit == editState.Adicionar)
                    {
                        cargoFuncionariosComboBox.Enabled = true;
                        cargoVeiculosComboBox_SelectedIndexChanged(null, null);
                    }

                    this.funcionariosPanel.Controls.Add(this.guardarButton);
                    break;
                case(viewState.Planeamentos):
                    this.planeamentosPanel.Controls.Add(this.guardarButton);
                    break;
                case(viewState.Veiculos):
                    matriculaVeiculoTextBox.ReadOnly = false;
                    tipoVeiculoTextBox.ReadOnly = false;
                    anoVeiculosTimePicker.Enabled = true;
                    larguraVeiculoTextBox.ReadOnly = false;
                    comprimentoVeiculoTextBox.ReadOnly = false;
                    depositoVeiculoTextBox.ReadOnly = false;
                    consumoVeiculoTextBox.ReadOnly = false;

                    this.veiculosPanel.Controls.Add(this.guardarButton);
                    break;
                default:
                    break;
            }
            guardarButton.Show();
        }

        // Clears text boxes
        private void clearTextBoxes()
        {
            switch (state)
            {
                case(viewState.Funcionarios):
                    idFuncionarioTextBox.Clear();
                    cargoFuncionariosComboBox.SelectedIndex = -1;
                    nomeFuncionarioTextBox.Clear();
                    dispFuncionariosTextBox.Clear();
                    tipoVeiculoFuncionariosCheckedListBox.Items.Clear();
                    fotoFuncionarioPictureBox.Image = null;
                    procurarFuncionariosButton.Hide();
                    break;
                case(viewState.Planeamentos):
                    condutorPlaneamentoTextBox.Clear();
                    veiculoPlaneamentoTextBox.Clear();
                    dataPlaneamentosTextBox.Clear();
                    dataGridView1.DataSource = null;
                    break;
                case(viewState.Veiculos):
                    idVeiculoTextBox.Clear();
                    matriculaVeiculoTextBox.Clear();
                    tipoVeiculoTextBox.Clear();
                    anoVeiculosTimePicker.Value = DateTime.Today;
                    larguraVeiculoTextBox.Clear();
                    comprimentoVeiculoTextBox.Clear();
                    depositoVeiculoTextBox.Clear();
                    consumoVeiculoTextBox.Clear();
                    break;
                case(viewState.Encomendas):
                    idEncomendasTextBox.Clear();
                    dataGridView2.DataSource = null;
                    larguraEncomendasTextBox.Clear();
                    comprimentoEncomendasTextBox.Clear();
                    idClienteEncomendasTextBox.Clear();
                    dataEncomendasTextBox.Clear();
                    break;
                case(viewState.Clientes):
                    idClientesTextBox.Clear();
                    nomeClientesTextBox.Clear();
                    prioridadeClientesTextBox.Clear();
                    idLocalClientesTextBox.Clear();
                    aberturaClientesTextBox.Clear();
                    fechoClientesTextBox.Clear();
                    break;
                case(viewState.Stock):
                    idStockTextBox.Clear();
                    tipoStocksTextBox.Clear();
                    quantidadesStocksTextBox.Clear();
                    dataStocksTextBox.Clear();
                    break;
                default:
                    break;
            }
        }

        private void sobreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBoxOPTFleet ab = new AboutBoxOPTFleet();
            this.AddOwnedForm(ab);
            ab.ShowDialog();
        }

        private void dataListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (setSelectedIndex)
            {
                setSelectedIndex = false;
                return;
            }
            if (dataListBox.SelectedIndex < 0) return;

            string selected = dataListBox.GetItemText(dataListBox.SelectedItem);
            char[] c = new char[1];
            selected = selected.Trim();
            char[] dumb = new char[1];
            dumb[0] = ' ';
            string[] aux = selected.Split(dumb,2);
            int id = int.Parse(aux[0]);
            Object[] args = new Object[2];
            args[0] = id;

            switch (state)
            {
                case viewState.Clientes:
                    string[] dias = {
                                        "Segunda-feira",
                                        "Terça-feira",
                                        "Quarta-feira",
                                        "Quinta-feira",
                                        "Sexta-feira"
                                    };
                    Cliente cliente = (Cliente)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_CLIENTE,args);
                    data = cliente;

                    idClientesTextBox.Text = cliente.IDcliente.ToString();
                    nomeClientesTextBox.Text = cliente.Nome;
                    prioridadeClientesTextBox.Text = cliente.Prioridade.ToString();
                    idLocalClientesTextBox.Text = cliente.Local.IDLocal.ToString();
                    aberturaClientesTextBox.Text = dias[cliente.Aberturajanela-1];
                    fechoClientesTextBox.Text = dias[cliente.Fechojanela-1];

                    break;
                case viewState.Encomendas:
                    Encomenda enc = (Encomenda)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_ENCOMENDA, args);
                    data = enc;

                    idEncomendasTextBox.Text = enc.IDencomenda.ToString();
                    larguraEncomendasTextBox.Text = enc.Largura.ToString();
                    comprimentoEncomendasTextBox.Text = enc.Comprimento.ToString();
                    idClienteEncomendasTextBox.Text = enc.Cliente.IDcliente.ToString();
                    dataEncomendasTextBox.Text = enc.Datapedido.ToString();

                    SortedDictionary<String, Int32> produtos = enc.Produtos;
                    DataTable table = new DataTable();
                    table.Columns.Add("Descrição", typeof(string));
                    table.Columns.Add("Quantidade", typeof(int));
                    foreach(string s in produtos.Keys)
                    {
                        table.Rows.Add(s, produtos[s]);
                    }
                    dataGridView2.DataSource = table;

                    break;
                case viewState.Funcionarios:
                    // Verify if another item is being edited
                    if (addEdit!=editState.View)
                    {
                        if (ignoreEditMessage())
                        {
                            if (permissao == CamadaDados.permissao.Admin)
                            {
                                adicionarButton.Enabled = true;
                                removerButton.Enabled = true;
                                editarButton.Enabled = true;
                            }
                            addEdit = editState.View;
                            lockTextBoxes();
                        }
                        else
                        {
                            setSelectedIndex = true;
                            dataListBox.SelectedIndex = selectedIndex;
                            return;
                        }
                    }

                    Funcionario fun = (Funcionario)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_FUNCIONARIO, args);
                    data = fun;

                    idFuncionarioTextBox.Text = fun.IDfuncionario.ToString();
                    nomeFuncionarioTextBox.Text = fun.Nome;
                    dispFuncionariosTextBox.Text = (fun.Disponivel)?"Disponível":"Indisponível";
                    cargoFuncionariosComboBox.SelectedText = fun.GetType().Name;
                    if (fun.GetType().Name.Equals("Motorista"))
                    {
                        cargoFuncionariosComboBox.SelectedIndex = 0;
                        tipoVeiculoFuncionariosCheckedListBox.Items.Clear();
                        SortedSet<int> tipos = ((Motorista)fun).TiposVeiculos;
                        bool b;
                        SortedDictionary<Int32, string> todos = (SortedDictionary<Int32, string>)cd.OperacaoDados(CamadaDados.OP_GET_TIPOS_VEICULOS, null);
                        foreach (Int32 i in todos.Keys)
                        {
                            b = (tipos.Contains(i)) ? true : false;
                            tipoVeiculoFuncionariosCheckedListBox.Items.Add(todos[i], b);
                        }
                        tipoVeiculoFuncionariosCheckedListBox.Enabled = false;
                    }
                    else
                    {
                        tipoVeiculoFuncionariosCheckedListBox.Items.Clear();
                        if (fun.GetType().Name.Equals("Gestor")) cargoFuncionariosComboBox.SelectedIndex = 1;
                        else cargoFuncionariosComboBox.SelectedIndex = 2;
                    }
                    fotoFuncionarioPictureBox.Image = new Bitmap(System.Drawing.Image.FromStream(new MemoryStream(fun.Foto)));

                    // Allow administrator to edit/remove
                    if (permissao == CamadaDados.permissao.Admin)
                    {
                        editarButton.Enabled = true;
                        removerButton.Enabled = true;
                    }

                    break;
                case viewState.Stock:
                    Stock stock = (Stock)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_STOCK, args);
                    data = stock;

                    idStockTextBox.Text = stock.IDStock.ToString();
                    tipoStocksTextBox.Text = stock.Nome;
                    quantidadesStocksTextBox.Text = stock.Quantidade.ToString();
                    dataStocksTextBox.Text = stock.DataValidade.ToString();

                    break;
                case viewState.Veiculos:
                    // Verify if another item is being edited
                    if (addEdit!=editState.View)
                    {
                        if (ignoreEditMessage())
                        {
                            if (permissao == CamadaDados.permissao.Admin)
                            {
                                adicionarButton.Enabled = true;
                                removerButton.Enabled = true;
                                editarButton.Enabled = true;
                            }
                            addEdit = editState.View;
                            lockTextBoxes();
                        }
                        else
                        {
                            setSelectedIndex = true;
                            dataListBox.SelectedIndex = selectedIndex;
                            return;
                        }
                    }

                    Veiculo v = (Veiculo)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_VEICULO, args);
                    data = v;

                    idVeiculoTextBox.Text = v.IDveiculo.ToString();
                    matriculaVeiculoTextBox.Text = v.Matricula;
                    switch (v.Tipo)
                    {
                        case Veiculo.LIGEIRO:
                            tipoVeiculoTextBox.Text = "Ligeiro";
                            break;
                        case Veiculo.PESADO:
                            tipoVeiculoTextBox.Text = "Pesado";
                            break;
                        case Veiculo.SEMIPESADO:
                            tipoVeiculoTextBox.Text = "Semi-pesado";
                            break;
                        default:
                            break;
                    }
                    anoVeiculosTimePicker.Value = v.Ano;
                    larguraVeiculoTextBox.Text = v.Largura.ToString();
                    comprimentoVeiculoTextBox.Text = v.Comprimento.ToString();
                    depositoVeiculoTextBox.Text = v.Deposito.ToString();
                    consumoVeiculoTextBox.Text = v.Consumomedio.ToString();

                    // Allow administrator to edit/remove
                    if (permissao == CamadaDados.permissao.Admin)
                    {
                        editarButton.Enabled = true;
                        removerButton.Enabled = true;
                    }

                    break;
                case viewState.Planeamentos:
                    // Verify if another item is being edited
                    if (addEdit!=editState.View)
                    {
                        if (ignoreEditMessage())
                        {
                            // editarButton.Enabled = true; // Not implemented yet.
                            addEdit = editState.View;
                            lockTextBoxes();
                        }
                        else
                        {
                            setSelectedIndex = true;
                            dataListBox.SelectedIndex = selectedIndex;
                            return;
                        };
                    }

                    args[1] = DateTime.Today;
                    Planeamento p = (Planeamento)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_PLANEAMENTO, args);
                    data = p;
                    condutorPlaneamentoTextBox.Text = p.Motorista.Nome;
                    veiculoPlaneamentoTextBox.Text = p.Veiculo.IDveiculo.ToString();
                    dataPlaneamentosTextBox.Text = p.Data.ToString();
                    DataTable tab = new DataTable();

                    tab.Columns.Add("Hora",typeof(string));
                    tab.Columns.Add("Encomenda",typeof(int));
                    tab.Columns.Add("Cliente", typeof(int));
                    tab.Columns.Add("Local", typeof(string));
                    foreach (Entrega entrega in p.Entregas)
                    {
                        tab.Rows.Add(entrega.Hora.Hour.ToString()+":"+entrega.Hora.Minute.ToString(), entrega.Encomenda.IDencomenda, entrega.Encomenda.Cliente.IDcliente, entrega.Encomenda.Cliente.Local.ToString());
                    }
                    dataGridView1.AutoResizeColumns();
                    dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                    dataGridView1.DataSource = tab;

                    // Allow user to edit
                    if (permissao != CamadaDados.permissao.Motorista)
                    {
                        //editarButton.Enabled = true; // Not implemented yet.
                    }

                    // Enable cargo visualization in the 'File' menu
                    visualizarCargaToolStripMenuItem.Enabled = true;

                    // Enable route visualization in the 'File' menu
                    visualizarRotaToolStripMenuItem.Enabled = true;

                    break;
                default:
                    break;
            }
            selectedIndex = dataListBox.SelectedIndex;
        }

        private void procurarFuncionariosButton_Click(object sender, EventArgs e)
        { 
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                //Image image = Image.FromFile(openFileDialog1.FileName);
                FileStream foto = (FileStream)openFileDialog1.OpenFile();
                System.Drawing.Image image = new Bitmap(foto);
                foto.Close();

                fotoFuncionarioPictureBox.Image = image;
            }
        }

        private void CreateCargasFile(string filename)
        {
            string dir = Directory.GetCurrentDirectory();
            List<string> lines = new List<string>();

            lines.Add(((Planeamento)data).Entregas.Count.ToString());
            lines.Add(((Planeamento)data).Veiculo.Largura.ToString());
            lines.Add(((Planeamento)data).Veiculo.Comprimento.ToString());
            foreach(Entrega e in ((Planeamento)data).Entregas)
            {
                lines.Add(e.Encomenda.Largura.ToString());
                lines.Add(e.Encomenda.Altura.ToString());
                lines.Add(e.Encomenda.Comprimento.ToString());
                lines.Add(e.PosX.ToString());
                lines.Add(e.PosY.ToString());
            }

            File.WriteAllLines(dir+"\\"+filename, lines);
        }

        private void visualizarCargaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Create the file that specifies the layout of the cargo in the vehicle 
            CreateCargasFile("cargas.optf");
       
            // Set up and launch the cargo visualizer
            string dir = Directory.GetCurrentDirectory();
            Process p = new Process();
            p.StartInfo.WorkingDirectory = dir;
            p.StartInfo.FileName = dir+"\\resources\\VisualizadorDeCarga.exe";
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            //p.StartInfo.Arguments = "whatever appropriate format & string of arguments";
            p.Start();
            p.WaitForExit();

            File.Delete("cargas.optf");
        }

        private void visualizarRotaToolStripMenuItem_Click(object sender, EventArgs e)
        { 
            Browser bw = new Browser(Operacoes.ParsePlaneamentoToURL((Planeamento)data));
            this.AddOwnedForm(bw);
            bw.ShowDialog(this);
        }

        private void cargoVeiculosComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cargoFuncionariosComboBox.SelectedIndex == 0)
            {
                tipoVeiculoFuncionariosCheckedListBox.Enabled = true;
                tipoVeiculoFuncionariosCheckedListBox.Items.Clear();
                tipoVeiculoFuncionariosCheckedListBox.Items.Add("Ligeiro", false);
                tipoVeiculoFuncionariosCheckedListBox.Items.Add("Semi-Pesado", false);
                tipoVeiculoFuncionariosCheckedListBox.Items.Add("Pesado", false);
            }
            else
            {
                tipoVeiculoFuncionariosCheckedListBox.Enabled = false;
                tipoVeiculoFuncionariosCheckedListBox.Items.Clear();
            }
        }

        private void pDFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Document pdf = new Document(PageSize.A4.Rotate());
            int selected = dataListBox.SelectedIndex;
            DialogResult result = DialogResult.Yes;
            Object[] args = new Object[2];
            int id;
            string[] aux;
            char[] dumb;
            char[] c;
            string s;

             try 
             {
            
            // step 2:
            // Now create a writer that listens to this doucment and writes the document to desired Stream.
            
            // step 4: Now add some contents to the document
            switch(state)
            {
                case(viewState.Clientes):
                    if (selected >= 0)
                    {
                        result = MessageBox.Show("Deseja exportar todos os clientes?", "Exportar para PDF", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    }
                    switch (result)
                    {
                        case DialogResult.Cancel:
                            return;
                        case DialogResult.No:
                            PdfWriter.GetInstance(pdf, new FileStream("Cliente_"+((Cliente)data).IDcliente+".pdf", FileMode.Create));
                            pdf.Open();
                            pdf.Add(new Paragraph(data.ToString()));
                            pdf.Close();
                            break;
                        case DialogResult.Yes:
                            PdfWriter.GetInstance(pdf, new FileStream("Clientes_"+DateTime.Today.DayOfYear.ToString()+".pdf", FileMode.Create));
                            pdf.Open();
                            for (int i = 0; i < dataListBox.Items.Count; i++)
                            {
                                s = dataListBox.GetItemText(dataListBox.Items[i]);
                                c = new char[1];
                                s = s.Trim();
                                dumb = new char[1];
                                dumb[0] = ' ';
                                aux = s.Split(dumb, 2);
                                id = int.Parse(aux[0]);
                                args[0] = id;

                                Cliente cliente = (Cliente)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_CLIENTE, args);
                                pdf.Add(new Paragraph(cliente.ToString()));
                            }
                            pdf.Close();
                            break;
                    }
                    break;
                case(viewState.Encomendas):
                    if (selected >= 0)
                    {
                        result = MessageBox.Show("Deseja exportar todas as encomendas?", "Exportar para PDF", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    }
                    switch (result)
                    {
                        case DialogResult.Cancel:
                            return;
                        case DialogResult.No:
                            PdfWriter.GetInstance(pdf, new FileStream("Encomenda_"+((Encomenda)data).IDencomenda+".pdf", FileMode.Create));
                            pdf.Open();
                            pdf.Add(new Paragraph(data.ToString()));
                            pdf.Close();;
                            break;
                        case DialogResult.Yes:
                            PdfWriter.GetInstance(pdf, new FileStream("Encomendas_"+DateTime.Today.DayOfYear.ToString()+".pdf", FileMode.Create));
                            pdf.Open();
                            for (int i = 0; i < dataListBox.Items.Count; i++)
                            {
                                s = dataListBox.GetItemText(dataListBox.Items[i]);
                                c = new char[1];
                                s = s.Trim();
                                dumb = new char[1];
                                dumb[0] = ' ';
                                aux = s.Split(dumb, 2);
                                id = int.Parse(aux[0]);
                                args[0] = id;

                                Encomenda cliente = (Encomenda)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_ENCOMENDA, args);
                                pdf.Add(new Paragraph(cliente.ToString()));
                            }
                            pdf.Close();
                            break;
                    }
                    break;
                case(viewState.Funcionarios):
                    if (selected >= 0)
                    {
                        result = MessageBox.Show("Deseja exportar todos os funcionários?", "Exportar para PDF", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    }
                    switch (result)
                    {
                        case DialogResult.Cancel:
                            return;
                        case DialogResult.No:
                            PdfWriter.GetInstance(pdf, new FileStream("Funcionario_"+((Funcionario)data).IDfuncionario+".pdf", FileMode.Create));
                            pdf.Open();
                            pdf.Add(new Paragraph(data.ToString()));
                            pdf.Close();
                            break;
                        case DialogResult.Yes:
                            PdfWriter.GetInstance(pdf, new FileStream("Funcionarios_"+DateTime.Today.DayOfYear.ToString()+".pdf", FileMode.Create));
                            pdf.Open();
                            for (int i = 0; i < dataListBox.Items.Count; i++)
                            {
                                s = dataListBox.GetItemText(dataListBox.Items[i]);
                                c = new char[1];
                                s = s.Trim();
                                dumb = new char[1];
                                dumb[0] = ' ';
                                aux = s.Split(dumb, 2);
                                id = int.Parse(aux[0]);
                                args[0] = id;

                                Funcionario cliente = (Funcionario)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_FUNCIONARIO, args);
                                pdf.Add(new Paragraph(cliente.ToString()));
                            }
                            pdf.Close();
                            break;
                    }
                    break;
                case(viewState.Init):
                    return;
                case(viewState.Planeamentos):
                    if (selected >= 0)
                    {
                        result = MessageBox.Show("Deseja exportar todos os planeamentos?", "Exportar para PDF", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    }
                    switch (result)
                    {
                        case DialogResult.Cancel:
                            return;
                        case DialogResult.No:
                            PdfWriter.GetInstance(pdf, new FileStream("Planeamento_"+((Planeamento)data).Data.DayOfYear.ToString()+"_"+((Planeamento)data).Motorista.IDfuncionario+"_"+((Planeamento)data).Veiculo.IDveiculo+".pdf", FileMode.Create));
                            pdf.Open();
                            pdf.Add(new Paragraph(data.ToString()));
                            pdf.Close();
                            break;
                        case DialogResult.Yes:
                            args[0] = DateTime.Today;
                            if (!((Boolean)cd.OperacaoDados(CamadaDados.PLANEAMENTOS_CALCULADOS, args)))
                            {
                                MessageBox.Show("Não existem planeamentos calculados!", "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                return;
                            }
                            PdfWriter.GetInstance(pdf, new FileStream("Planeamentos_"+DateTime.Today.DayOfYear.ToString()+".pdf", FileMode.Create));
                            pdf.Open();
                            List<Planeamento> lista = (List<Planeamento>)cd.OperacaoDados(CamadaDados.OP_GET_PLANEAMENTOS, args);
                            foreach(Planeamento p in lista){
                                pdf.Add(new Paragraph(p.ToString()));
                            }
                            pdf.Close();
                            break;
                    }
                    break;
                case(viewState.Stock):
                    if (selected >= 0)
                    {
                        result = MessageBox.Show("Deseja exportar todos os produtos em stock?", "Exportar para PDF", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    }
                    switch (result)
                    {
                        case DialogResult.Cancel:
                            return;
                        case DialogResult.No:
                            PdfWriter.GetInstance(pdf, new FileStream("Produto_"+((Stock)data).IDStock+".pdf", FileMode.Create));
                            pdf.Open();
                            pdf.Add(new Paragraph(data.ToString()));
                            pdf.Close();
                            break;
                        case DialogResult.Yes:
                            PdfWriter.GetInstance(pdf, new FileStream("Stock_"+DateTime.Today.DayOfYear.ToString()+".pdf", FileMode.Create));
                            pdf.Open();
                            for (int i = 0; i < dataListBox.Items.Count; i++)
                            {
                                s = dataListBox.GetItemText(dataListBox.Items[i]);
                                c = new char[1];
                                s = s.Trim();
                                dumb = new char[1];
                                dumb[0] = ' ';
                                aux = s.Split(dumb, 2);
                                id = int.Parse(aux[0]);
                                args[0] = id;

                                Stock cliente = (Stock)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_STOCK, args);
                                pdf.Add(new Paragraph(cliente.ToString()));
                            }
                            pdf.Close();
                            break;
                    }
                    break;
                case (viewState.Veiculos):
                    if (selected >= 0)
                    {
                        result = MessageBox.Show("Deseja exportar todos os veículos?", "Exportar para PDF", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    }
                    switch (result)
                    {
                        case DialogResult.Cancel:
                            return;
                        case DialogResult.No:
                            PdfWriter.GetInstance(pdf, new FileStream("Veiculo_"+((Veiculo)data).IDveiculo+".pdf", FileMode.Create));
                            pdf.Open();
                            pdf.Add(new Paragraph(data.ToString()));
                            pdf.Close();
                            break;
                        case DialogResult.Yes:
                            PdfWriter.GetInstance(pdf, new FileStream("Veiculos_"+DateTime.Today.DayOfYear.ToString()+".pdf", FileMode.Create));
                            pdf.Open();
                            for (int i = 0; i < dataListBox.Items.Count; i++)
                            {
                                s = dataListBox.GetItemText(dataListBox.Items[i]);
                                c = new char[1];
                                s = s.Trim();
                                dumb = new char[1];
                                dumb[0] = ' ';
                                aux = s.Split(dumb, 2);
                                id = int.Parse(aux[0]);
                                args[0] = id;

                                Veiculo cliente = (Veiculo)cd.OperacaoDados(CamadaDados.OP_CONSULTAR_VEICULO, args);
                                pdf.Add(new Paragraph(cliente.ToString()));
                            }
                            pdf.Close();
                            break;
                    }
                    break;
            }
            
            }
            catch(DocumentException de) 
            {
            Console.Error.WriteLine(de.Message);
            }
            catch(IOException ioe) 
            {
            Console.Error.WriteLine(ioe.Message);
            }
        }

        private void hTMLToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
    }
}